package com.xjrsoft.module.erpModel.caseErpCustomer.controller;

import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.lang.TypeReference;
import cn.hutool.core.util.StrUtil;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.support.ExcelTypeEnum;
import com.baomidou.mybatisplus.core.toolkit.StringPool;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.xjrsoft.common.annotation.XjrLog;
import com.xjrsoft.common.constant.GlobalConstant;
import com.xjrsoft.common.enums.YesOrNoEnum;
import com.xjrsoft.common.model.result.R;
import com.xjrsoft.common.utils.RedisUtil;
import com.xjrsoft.module.erpModel.caseErpCustomer.dto.*;
import com.xjrsoft.module.erpModel.caseErpCustomer.entity.CaseErpCustomer;
import com.xjrsoft.module.erpModel.caseErpCustomer.service.ICaseErpCustomerService;
import com.xjrsoft.module.erpModel.caseErpCustomer.vo.*;
import com.xjrsoft.module.erpModel.caseErpLog.entity.CaseErpLog;
import com.xjrsoft.module.organization.entity.User;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import lombok.SneakyThrows;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.validation.Valid;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;


/**
 * <p>
 * 客户信息【case_erp_customer】 前端控制器
 * </p>
 *
 * @author hnyyzy
 * @since 2023-07-11
 */
@RestController
@RequestMapping(GlobalConstant.CASE_ERP_CUSTOMER+"/caseErpCustomer")
@Api(value = GlobalConstant.CASE_ERP_CUSTOMER +"/caseErpCustomer", tags = "客户信息")
@AllArgsConstructor
public class CaseErpCustomerController {
    private ICaseErpCustomerService caseErpCustomerService;

    private RedisUtil redisUtil;

    @GetMapping(value = "/list")
    @ApiOperation("所以客户列表，不分页")
    public R list() {
        List<CaseErpCustomer> list = caseErpCustomerService.list();
        List<CaseErpCustomerListVo> caseErpCustomerListVos = BeanUtil.copyToList(list, CaseErpCustomerListVo.class);
        List<User> userList = redisUtil.get(GlobalConstant.USER_CACHE_KEY, new TypeReference<List<User>>() {
        });
        for (CaseErpCustomerListVo caseErpCustomerListVo : caseErpCustomerListVos) {
            if (StrUtil.isNotBlank(caseErpCustomerListVo.getSaleIds())){
                String allUserIdStr = StrUtil.join(StringPool.COMMA, caseErpCustomerListVo.getSaleIds());
                List<Long> ids = Arrays.stream(allUserIdStr.split(StringPool.COMMA)).map(Convert::toLong).collect(Collectors.toList());
                List<String> names = userList.stream().filter(x -> ids.contains(x.getId())).map(User::getName).collect(Collectors.toList());
                if (CollectionUtil.isNotEmpty(names)){
                    caseErpCustomerListVo.setSaleNames(StrUtil.join(StringPool.COMMA,names));
                }
            }
            caseErpCustomerListVo.setSalePhone("18333333333");
        }
        return R.ok(caseErpCustomerListVos);
    }

    @GetMapping(value = "/page")
    @ApiOperation("客户信息、客户公海列表分页")
    public R page(CaseErpCustomerDto dto) {
        return R.ok(caseErpCustomerService.getPageList(dto));
    }

    @PostMapping
    @ApiOperation(value = "新增客户信息、公海信息")
    public R add(@Valid @RequestBody AddCaseErpCustomerDto dto) {
        long count = caseErpCustomerService.count(Wrappers.<CaseErpCustomer>query().lambda().eq(CaseErpCustomer::getName, dto.getName()));
        if (count > 0) {
            return R.error("此客户信息已经存在！");
        }
        return R.ok(caseErpCustomerService.add(dto));
    }

    @PutMapping
    @ApiOperation(value = "修改客户信息、公海信息")
    public R update(@Valid @RequestBody UpdateCaseErpCustomerDto dto) {
        return R.ok(caseErpCustomerService.update(dto));
    }

    @GetMapping(value = "/info")
    @ApiOperation(value = "根据id查询客户信息、公海信息（返回id值，编辑使用）")
    public R info(@RequestParam Long id) {
        CaseErpCustomer caseErpCustomer = caseErpCustomerService.getById(id);
        if (caseErpCustomer == null) {
            R.error("找不到此客户信息！");
        }
        CaseErpCustomerInfoVo caseErpCustomerInfoVo = caseErpCustomerService.info(caseErpCustomer);
        return R.ok(caseErpCustomerInfoVo);
    }

    @GetMapping(value = "/base-info")
    @ApiOperation(value = "根据id查询客户基本信息（返回名称值，详情查看使用）")
    public R baseInfo(@RequestParam Long id) {
        CaseErpCustomer caseErpCustomer = caseErpCustomerService.getById(id);
        if (caseErpCustomer == null) {
            R.error("找不到此客户信息！");
        }
        CaseErpCustomerVo caseErpCustomerVo = caseErpCustomerService.baseInfo(caseErpCustomer);
        return R.ok(caseErpCustomerVo);
    }


    @DeleteMapping
    @ApiOperation(value = "删除")
    @XjrLog(value = "删除客户信息、公海信息")
    public R delete(@Valid @RequestBody Long id) {
        return R.ok(caseErpCustomerService.delete(id));
    }

    @PutMapping("/common")
    @ApiOperation(value = "移入公海")
    public R common(@Valid @RequestBody List<Long> ids) {
        return R.ok( caseErpCustomerService.common(ids));
    }

    @PutMapping("/transfer")
    @ApiOperation(value = "转移")
    public R transfer(@Valid @RequestBody TransferCaseErpCustomerDto dto) {
        return R.ok( caseErpCustomerService.transfer(dto));
    }

    @PostMapping(value = "/export")
    @ApiOperation(value = "客户列表导出")
    @XjrLog(value = "导出表单数据")
    public ResponseEntity<byte[]> export(@RequestBody List<Long> ids) {
        List<CaseErpCustomerExportVo> exportVoList = caseErpCustomerService.export(ids);
        ByteArrayOutputStream bot = new ByteArrayOutputStream();
        EasyExcel.write(bot, CaseErpCustomerExportVo.class).excelType(ExcelTypeEnum.XLSX).sheet().doWrite(exportVoList);
        return R.fileStream(bot.toByteArray(), "客户列表" + ExcelTypeEnum.XLSX.getValue());
    }

    @PostMapping("/import")
    @ApiOperation(value = "客户列表导入")
    public R importData(@RequestParam MultipartFile file) throws IOException {
        return R.ok(caseErpCustomerService.importData(file));
    }

    @GetMapping("/export")
    @ApiOperation(value = "客户列表下载模板")
    @SneakyThrows
    public ResponseEntity<byte[]> export() {
        List<ImportCaseErpCustomerDto> importCaseErpUnitDtos = new ArrayList<>();
        ByteArrayOutputStream bot = new ByteArrayOutputStream();
        EasyExcel.write(bot, ImportCaseErpCustomerDto.class).excelType(ExcelTypeEnum.XLSX).sheet().doWrite(BeanUtil.copyToList(importCaseErpUnitDtos, ImportCaseErpCustomerDto.class));
        return R.fileStream(bot.toByteArray(), "客户列表模板" + ExcelTypeEnum.XLSX.getValue());
    }

    @PostMapping(value = "/export-common")
    @ApiOperation(value = "客户公海导出")
    @XjrLog(value = "导出表单数据")
    public ResponseEntity<byte[]> exportCommonAll() {
        List<CaseErpCustomerCommonExportVo> exportVoList = caseErpCustomerService.exportCommon();
        ByteArrayOutputStream bot = new ByteArrayOutputStream();
        EasyExcel.write(bot, CaseErpCustomerCommonExportVo.class).excelType(ExcelTypeEnum.XLSX).sheet().doWrite(exportVoList);
        return R.fileStream(bot.toByteArray(), "客户公海" + ExcelTypeEnum.XLSX.getValue());
    }

    @PostMapping("/import-common")
    @ApiOperation(value = "客户公海导入")
    public R importCommonData(@RequestParam MultipartFile file) throws IOException {
        return R.ok(caseErpCustomerService.importCommonData(file));
    }

    @GetMapping("/export-common")
    @ApiOperation(value = "客户公海下载模板")
    @SneakyThrows
    public ResponseEntity<byte[]> exportCommon() {
        List<ImportCaseErpCustomerDto> importCaseErpUnitDtos = new ArrayList<>();
        ByteArrayOutputStream bot = new ByteArrayOutputStream();
        EasyExcel.write(bot, ImportCaseErpCustomerDto.class).excelType(ExcelTypeEnum.XLSX).sheet().doWrite(BeanUtil.copyToList(importCaseErpUnitDtos, ImportCaseErpCustomerDto.class));
        return R.fileStream(bot.toByteArray(), "客户公海模板" + ExcelTypeEnum.XLSX.getValue());
    }

    @GetMapping(value = "/detail-info")
    @ApiOperation(value = "根据id查询详情信息")
    public R detailInfo(@RequestParam Long id) {
        CaseErpCustomer caseErpCustomer = caseErpCustomerService.getById(id);
        if (caseErpCustomer == null) {
            R.error("找不到此客户信息！");
        }
        return R.ok(caseErpCustomerService.detailInfo(caseErpCustomer));
    }

    @PutMapping(value = "/get-from-common")
    @ApiOperation(value = "根据id领取客户")
    public R getFromCommon(@Valid @RequestBody TransferCaseErpCustomerDto dto) {
        return R.ok(caseErpCustomerService.getFromCommon(dto.getId()));
    }


    @GetMapping("/customer-source")
    @ApiOperation(value="客户来源统计")
    public R customerSource() {
        return R.ok(caseErpCustomerService.getCustomerSource());
    }

    @GetMapping("/customer-statistics")
    @ApiOperation(value="统计今日客户数据")
    public R customerStatistics() {
        return R.ok(caseErpCustomerService.getAll());
    }

    @GetMapping("/customer-gather")
    @ApiOperation(value="客户回款")
    public R customerGather() {
        return R.ok(caseErpCustomerService.getCustomerPaymexnt());
    }

    @GetMapping("/customer-type")
    @ApiOperation(value="客户类型分布")
    public R getCustomerType() {
        return R.ok(caseErpCustomerService.getCustomerType());
    }
}
